#include "finish.h"

Finish::Finish(QWidget *parent)
	: QWidget(parent)
{
	ui.setupUi(this);

	QVBoxLayout *layout = (QVBoxLayout *)ui.widFinishList->layout();
	layout->setDirection(QBoxLayout::BottomToTop);
	ui.widFinishList->setLayout(layout);

	loadFinishData();
}

Finish::~Finish() {
}

void Finish::loadFinishData() {
	QMap<QString, FinishItem*>::iterator iter = m_finishMap.begin();
	while (iter != m_finishMap.end()) {
		ui.widFinishList->layout()->removeWidget(iter.value());
		disconnect(iter.value());
		iter++;
	}
	qDeleteAll(m_finishMap);
	m_finishMap.clear();

	QSqlQuery query;
	//QString sql = QString("select * from T_UPLOAD where STATUS<>'%1';").arg(UPLOAD_STATUS_FINISH);
	QString sql = QString("select * from (select ID,NAME,TIME,0 from T_DOWNLOAD where STATUS='%1' union "
		"select ID,FILE_PATH,TIME,1 from T_UPLOAD where STATUS='%2') order by TIME asc;").arg(DOWNLOAD_STATUS_FINISH).arg(UPLOAD_STATUS_FINISH);
	if (!query.exec(sql)) {
		SSMS_INFO(query.lastError().text().toStdString().c_str());
	}
	else {
		while (query.next()) {
			QString itemID = query.value(0).toString();
			QString filePath = query.value(1).toString();
			QString time = query.value(2).toString();
			int flag = query.value(3).toInt();
			SSMS_INFO("itemID:" << itemID.toStdString().c_str() << ",filePath:" << filePath.toStdString().c_str() << ",time:" << time.toStdString().c_str() << ",flag:" << flag);
			addFinishItem(itemID, filePath, time, flag);
		}
	}
}

void Finish::addFinishItem(QString itemID, QString filePath, QString time, int flag) {
	FinishItem *finishItem = new FinishItem(itemID, filePath, time, flag);
	connect((const QObject *)finishItem, SIGNAL(openDirSignal(QString)), this, SLOT(openDirSlot(QString)));
	connect((const QObject *)finishItem, SIGNAL(clearSignal(QString)), this, SLOT(clearSlot(QString)));
	ui.widFinishList->layout()->addWidget(finishItem);
	m_finishMap[itemID] = finishItem;
}

void Finish::openDirSlot(QString itemID) {
	QDesktopServices::openUrl(QUrl(GlobalData::fileStorageDir, QUrl::TolerantMode));
}

void Finish::clearSlot(QString itemID) {
	QSqlQuery query;
	QString sql = QString("delete from T_UPLOAD where ID='%1';").arg(itemID);
	if (!query.exec(sql)) {
		SSMS_INFO(query.lastError().text().toStdString().c_str());
	}
	else {
		SSMS_INFO("delete T_UPLOAD success." << sql.toStdString().c_str());
	}

	sql = QString("delete from T_DOWNLOAD where ID='%1';").arg(itemID);
	if (!query.exec(sql)) {
		SSMS_INFO(query.lastError().text().toStdString().c_str());
	}
	else {
		SSMS_INFO("delete T_DOWNLOAD success." << sql.toStdString().c_str());
	}
	ui.widFinishList->layout()->removeWidget(m_finishMap[itemID]);
	delete m_finishMap[itemID];
	m_finishMap.remove(itemID);
}

void Finish::refreshFinishSlot() {
	loadFinishData();
}
